package com.yy.invoice.utils;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class FileUtils {

    public static String fileUpload(MultipartFile file,String accessKey,String secretKey,String bucket,String fileUrl){
        String key = null;
        try {
            Auth auth = Auth.create(accessKey,secretKey);
            Configuration configuration = new Configuration();
            UploadManager uploadManager = new UploadManager(configuration);
            String token = auth.uploadToken(bucket);
            key = DigestUtils.md5DigestAsHex(file.getInputStream());
            String end = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            Response response = uploadManager.put(file.getInputStream(), key + end, token,null,null);
            if(response.statusCode == 200){
                return fileUrl + key + end;
            }else{
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String fileUpload(File file,String accessKey,String secretKey,String bucket,String fileUrl){
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            String key =  DigestUtils.md5DigestAsHex(inputStream) + "-" + file.getName();
            Auth auth = Auth.create(accessKey,secretKey);
            Configuration configuration = new Configuration();
            UploadManager uploadManager = new UploadManager(configuration);
            String token = auth.uploadToken(bucket,key);
            Response response = uploadManager.put(file, key, token);
            if(response.statusCode == 200){
                return fileUrl + key;
            }else{
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 下载远程文件并保存到本地
     *
     * @param remoteFilePath-远程文件路径
     * @param localFilePath-本地文件路径（带文件名）
     * http://q5qobmi0y.bkt.clouddn.com/01.jpg
     */
    public static void downloadFile(String remoteFilePath, String localFilePath) {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将多个PDF装换成一个PDF
     * @param files
     * @param targetPath
     * @return
     * @throws Exception
     */
    public static String MulFileToOne(File[] files, String targetPath) throws Exception {
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if(f.exists() && f.isFile()){
                // 循环添加要合并的pdf
                mergePdf.addSource(f);
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(targetPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return targetPath;
    }
}
